package com.wecan.es.learning.controller;

import com.alibaba.fastjson.JSONObject;
import com.yyh.elasticsearch.entity.Good;
import com.yyh.elasticsearch.service.GoodService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @ClassName:GoodController
 * @Description: es 的一个demo
 * @Author: yaoyonghao
 * @Date: 2019/3/5、10:33
 */
@RestController
public class GoodController {
    @Autowired
    private GoodService goodService;

    /**
     * 添加数据
     *
     * @param title
     * @param category
     * @param brand
     * @param price
     * @param images
     * @return String
     */
    @ApiOperation(value = "保存数据", notes = "保存数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "category", value = "分类", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "brand", value = "品牌", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "price", value = "价格", paramType = "query", required = true, dataType = "Double"),
            @ApiImplicitParam(name = "images", value = "图片", paramType = "query", required = true, dataType = "String")
    })
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @PostMapping("/save")
    public String save(@RequestParam(value = "title", required = true) String title,
                       @RequestParam("category") String category,
                       @RequestParam("brand") String brand,
                       @RequestParam(value = "price", defaultValue = "0.0") Double price,
                       @RequestParam("images") String images) {

        Good goodinfo = new Good(System.currentTimeMillis(), title, category, brand, price, images);
        goodService.saveGoods(goodinfo);
        return "success";
    }

    /**
     * 查詢所有的数据
     *
     * @return
     */
    @ApiOperation(value = "查询所有数据", notes = "查询所有数据")
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @GetMapping("/list")
    public JSONObject findAll() {
        JSONObject object = goodService.findAll();
        return object;
    }

    /**
     * 通过id删除数据
     *
     * @param id 获取的id
     * @return
     */
    @ApiOperation(value = "通过id删除数据", notes = "通过id删除数据")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "String")
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @DeleteMapping("/delete")
    public String delete(@RequestParam(value = "id", required = true) Long id) {
        goodService.deleteGoodById(id);
        return "success";
    }

    /**
     * @param
     * @return
     * @Title
     * @Description: 更新
     * @author yaoyonghao
     * @date 2019/3/5 14:31
     */
    @ApiOperation(value = "更新货物信息", notes = "更新货物信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "title", value = "标题", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "category", value = "分类", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "brand", value = "品牌", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "price", value = "价格", paramType = "query", required = false, dataType = "Double"),
            @ApiImplicitParam(name = "images", value = "图片", paramType = "query", required = false, dataType = "String")
    })
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @PostMapping("/update")
    public String update(@RequestParam(value = "id", required = true) Long id,
                         @RequestParam(value = "title", required = false) String title,
                         @RequestParam(value = "category", required = false) String category,
                         @RequestParam(value = "brand", required = false) String brand,
                         @RequestParam(value = "price", required = false) Double price,
                         @RequestParam(value = "images", required = false) String images) {

        Good goodinfo = new Good(id, title, category, brand, price, images);
        goodService.updateGoods(goodinfo);
        return "success";
    }


    /**
     * 分页模糊查询
     *
     * @param pageNum
     * @param pageSize
     * @param query
     * @return com.alibaba.fastjson.JSONObject;
     */
    @ApiOperation(value = "分页模糊查询", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "起始位置", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "size大小", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "query", value = "查询条件", paramType = "query", required = true, dataType = "String")
    })
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @GetMapping("/search/page")
    public JSONObject getListByPage(@RequestParam(value = "pageNum") Integer pageNum,
                                    @RequestParam(value = "pageSize") Integer pageSize,
                                    @RequestParam(value = "query") String query) {
        JSONObject jsonObject = goodService.queryListByPage(pageNum, pageSize, query);
        return jsonObject;

    }


    /**
     * 进行简单的模糊查询
     *
     * @param searchContent
     * @return
     */
    @GetMapping("/search/{searchContent}")
    public JSONObject searchContent(@PathVariable(value = "searchContent") String searchContent) {
        JSONObject jsonObject = goodService.searchContent(searchContent);
        return jsonObject;
    }

    /**
     * @param searchContent
     * @return
     */
    @GetMapping("/search/weight")
    public JSONObject searchContentByWeight(String searchContent) {
//        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
//                .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", searchContent)),
//                        ScoreFunctionBuilders.weightFactorFunction(10))
//                .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),
//                        ScoreFunctionBuilders.weightFactorFunction(100)).setMinScore(2);
        return null;
    }

    /**
     * 非聚合复杂查询
     *
     * @return
     */
    @ApiOperation(value = "分页模糊查询", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "起始位置", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "size大小", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "title", value = "查询字段", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "brand", value = "查询字段", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sort", value = "排序方式", paramType = "query", required = true, dataType = "String")
    })
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @GetMapping("/search/condition")
    public JSONObject searchComplexByCondition(String title, String brand, Integer pageNum, Integer pageSize, String sort) {
        JSONObject jsonObject = goodService.searchComplexByCondition(title, brand, pageNum, pageSize, sort);
        return jsonObject;

    }

    @ApiOperation(value = "通过拼音分词器对中文模糊查询", notes = "通过拼音分词器对中文模糊查询")
    @ApiImplicitParam(name = "brand", value = "品牌", paramType = "query", required = true, dataType = "String")
    @GetMapping("/search/pinyin")
    public JSONObject searchByPinyin(String brand) {
        return goodService.searchByPinyin(brand);
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8686/queryHit?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc
     *
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @ApiOperation(value = "搜索命中关键字高亮", notes = "搜索命中关键字高亮")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "indexName", value = "索引库名称", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "fields", value = "搜索字段名称", paramType = "query", required = true, dataType = "String")
    })
    @ApiResponse(message = "响应", code = 200, response = JSONObject.class)
    @GetMapping("/queryHit")
    public List<Map<String, Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields) {
        String[] fieldNames = {};
        if (fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return goodService.queryHit(keyword, indexName, fieldNames);
    }
    /**
     *
     * （1）统计某个字段的数量
     *   ValueCountBuilder vcb=  AggregationBuilders.count("count_uid").field("uid");
     * （2）去重统计某个字段的数量（有少量误差）
     *  CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");
     * （3）聚合过滤
     * FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));
     * （4）按某个字段分组
     * TermsBuilder tb=  AggregationBuilders.terms("group_name").field("name");
     * （5）求和
     * SumBuilder  sumBuilder=	AggregationBuilders.sum("sum_price").field("price");
     * （6）求平均
     * AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");
     * （7）求最大值
     * MaxBuilder mb= AggregationBuilders.max("max_price").field("price");
     * （8）求最小值
     * MinBuilder min=	AggregationBuilders.min("min_price").field("price");
     * （9）按日期间隔分组
     * DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");
     * （10）获取聚合里面的结果
     * TopHitsBuilder thb=  AggregationBuilders.topHits("top_result");
     * （11）嵌套的聚合
     * NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");
     * （12）反转嵌套
     * AggregationBuilders.reverseNested("res_negsted").path("kps ");
     */
}
